<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Validate;
use think\model\concern\SoftDelete;
use org\QRcode;
use think\facade\Log;

class Device extends Common
{
    //软删除位
    use SoftDelete;
    protected $deleteTime = 'isdel';

    //时间自动存储
    protected $autoWriteTimestamp = true;
    protected $createTime = 'ctime';
    protected $updateTime = 'utime';
     
    protected $rule =   [
        'name'              =>  'require|max:50',
        'cat_id'            =>  'require',
        'brand_id'          =>  'require', 
        'type_id'           =>  'require', 
        'sub_id'            =>  'require', 
        'area_id'           =>  'require'
    ];

    protected $msg  =   [
        'name.require'              =>  '请输入模板名称',
        'name.max'                  =>  '模板名最多不能超过50个字符',
        'cat_id.require'            =>  '请选择设备分类',
        'brand_id.require'          =>  '请选择设备品牌', 
        'type_id.require'           =>  '请选择设备使用场景', 
        'area_id.require'           =>  '请选择设备位置', 
        'sub_id.require'            =>  '请输入厂家设备ID'
    ];

    const DEVICE_STATUS_YES = 1;      //启用
    const DEVICE_STATUS_NO  = 2;      //禁用

    /**
     * 设置csv header
     * @return array
     */
    public function csvHeader()
    {
        return [
            [
                'id'   => 'name',
                'desc' => '设备名称',
            ],
            [
                'id'   => 'cat_id',
                'desc' => '类型名称',
            ],
            [
                'id'   => 'brand_id',
                'desc' => '品牌名称',
            ],
            [
                'id'   => 'type_id',
                'desc' => '使用场景',
            ],
            [
                'id'   => 'sub_id',
                'desc' => '出厂编号',
            ],
            [
                'id'   => 'area_id',
                'desc' => '设备位置',
            ],
            [
                'id'   => 'status',
                'desc' => '状态',
            ]
        ];
    }

    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }

        $tableWhere = $this->tableWhere($post);
        $list = $this->alias('device')
                        ->field("device.id, device.cat_id, device.brand_id, device.type_id, device.name, device.area_id, device.sub_id, device.status, device.qrcode, device.ctime, device.utime, cat.name as cat_name, type.name as type_name, brand.name as brand_name")
                        ->join('zl_device_cat cat', 'device.cat_id = cat.id')
                        ->leftjoin('zl_brand brand', 'device.brand_id = brand.id')
                        ->leftjoin('zl_device_type type', 'device.type_id = type.id')
                        ->leftjoin('zl_area area', 'device.area_id = area.id')
                        ->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;
        return $re;
    }

    /**
     *  添加模板方法
     * User:tony
     * @param $data
     * @return array
     */
    public function addData($data)
    {
        $validate = new Validate($this->rule,$this->msg);
        $result = ['status' => true, 'msg' => '保存成功' , 'data' => ''];
        if(!$validate->check($data))
        {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            if (!$this->allowField(true)->save($data)) {
                $result['status'] = false;
                $result['msg'] = '保存失败';
            } else {
                //设置计费规则关联
                $deviceTemplateRel = new DeviceTemplateRel();
    
                //清空所有的计费规则
                $deviceTemplateRel->where(['device_id'=>$this->id])->delete();
            
                if(isset($data['template_id'])){
                    $data1 = [];
                    foreach($data['template_id'] as $k => $v){
                        $row['device_id'] = $this->id;
                        $row['template_id'] = $k;
                        $data1[] = $row;
                    }
                    $deviceTemplateRel->saveAll($data1);
                }

                $return['status'] = true;
                $return['msg']    = '保存成功'; 
            }
        }
        return $result;
    }
 
    /**
     *  修改模板信息
     * User:tony
     * @param $data
     * @return array
     */
    public function saveData($data)
    {
        $validate = new Validate($this->rule,$this->msg);
        $result = ['status' => true, 'msg' => '保存成功' , 'data' => ''];

        if(isset($data['status']) && $data['status'] == 1){
        }else{
            $data['status'] = 2;
        }

        if(!$validate->check($data))
        {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            if (!$this->allowField(true)->save($data, ['id'=>$data['id']])) {
                $result['status'] = false;
                $result['msg'] = '保存失败';
            } else {
                //设置计费规则关联
                $deviceTemplateRel = new DeviceTemplateRel();
    
                //清空所有的计费规则
                $deviceTemplateRel->where(['device_id'=>$data['id']])->delete();
            
                if(isset($data['template_id'])){
                    $data1 = [];
                    foreach($data['template_id'] as $k => $v){
                        $row['device_id'] = $this->id;
                        $row['template_id'] = $k;
                        $data1[] = $row;
                    }
                    $deviceTemplateRel->saveAll($data1);
                }

                $return['status'] = true;
                $return['msg']    = '保存成功'; 
            }
        }
        return $result;

    }
 
    /**
     *  table WHERE搜索
     * User:tony
     * @param $post
     * @return mixed
     */
    protected function tableWhere($post)
    {
        $where = [];
        if(isset($post['name']) && $post['name'] != ""){
            $where[] = ['name', 'like', '%'.$post['name'].'%'];
        }

        if(isset($post['type_id']) && $post['type_id'] != ""){
            $where[] = ['type_id', 'eq', $post['type_id']];
        }

        if(isset($post['cat_id']) && $post['cat_id'] != ""){
            $where[] = ['cat_id', 'eq', $post['cat_id']];
        }
         
        if(isset($post['brand_id']) && $post['brand_id'] != ""){
            $where[] = ['brand_id', 'eq', $post['brand_id']];
        }
         
        if(isset($post['sub_id']) && $post['sub_id'] != ""){
            $where[] = ['sub_id', 'like', '%'.$post['sub_id'].'%'];
        }

        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = 'cat_id asc, brand_id asc, type_id asc, area.sort asc';
        return $result;
    }

    protected function tableFormat($list)
    {
        foreach ( $list as $key => $val ) {
            $brandModel = new Brand();
            $deviceCatModel = new DeviceCat();
            $deviceTypeModel = new DeviceType();

            $list[$key]['area'] = get_area($val['area_id']);
            $list[$key]['ctime'] = date('Y-m-d H:i:s', $val['ctime']);
            $list[$key]['utime'] = date('Y-m-d H:i:s', $val['utime']);
        }
        return $list;
    }
 
    /**
     *
     * 快捷更改状态
     * @param $id
     * @param $status
     * @return array
     */
    public function changeStatus($id,$status)
    {
        $result = ['status'=>true,'msg'=>'','data'=>''];
        $where['id'] = $id;

        switch($status)
        {
            case 'true':
                $this->save(['status'=>self::DEVICE_STATUS_YES],$where);
                $result['msg'] = '已'.config('params.payments')['status'][self::DEVICE_STATUS_YES];
                break;
            case 'false':
                $this->save(['status'=>self::DEVICE_STATUS_NO],$where);
                $result['msg'] = '已'.config('params.payments')['status'][self::DEVICE_STATUS_NO];
                break;
            default:
                $result['status'] = false;
                $result['msg'] = '非法操作';
                break;
        }

        return $result;
    }

    /**
     *
     * 获取设备二维码
     * @param $id
     * @param $status
     * @return array
     */
    public function GetWxCode($id)
    {  
        $deviceInfo = $this->where(['id' => $id])->find();
        if (!$deviceInfo) {
            return false;
        }
         
        include_once ROOT_PATH . 'extend/org/phpqrcode.php';
        $path = '../public/static/qrcode/blower/ziyu/' . $deviceInfo['sub_id'] . '.png'; 
        // 如果之前没有创建过二维码，首先生成二维码
        //判断文件是否存在如果不存在需要重新生成
        if(!file_exists($path) || !$deviceInfo['qrcode']){
            
            $url = getRealUrl('/static/qrcode/blower/ziyu/' . $deviceInfo['sub_id'] . '.png');
            $qrc_data = "https://zlhq.zhongliansoft.com/blower/ziyu/".$deviceInfo['sub_id']."-0";
            
            // 生成二维码
            QRcode::png($qrc_data, $path, 'L', 10, 2);

            $uData = [
                'qrcode' => $url,
            ];
    
            $this->save($uData, [
                'id' => $deviceInfo['id'],
            ]);

            return $url;
        }

        return $deviceInfo['qrcode'];
    }
    
    /**
     * 获取设备信息
     * @return array
     */
    public function getDeviceInfo($id)
    {
        $result = ['status' => false, 'msg' => '' , 'data' => ''];
        $deviceInfo = $this->where(['id' => $id])->find();

        if(!$deviceInfo) {
            return error_code(10002);
        }
 
        $result['data'] = $deviceInfo; 
        return $result;
    } 
 
    /**
     * 返回deviceList
     * @author tony
     * @param $post
     * @return mixed
     */
    public function getDeviceList()
    {
        $list       = [];
        $list = $this->alias('dev')
                    ->field('cat.name catName, brand.name brandName, type.name typeName, dev.sub_id')
                    ->join(config('database.prefix') . 'device_cat cat', 'cat.id = dev.cat_id', 'left')
                    ->join(config('database.prefix') . 'brand brand', 'brand.id = dev.brand_id', 'left')
                    ->join(config('database.prefix') . 'device_type type', 'type.id = dev.type_id', 'left')->select();

        $deviceArray = $list->toArray();
        $deviceList = [];
        foreach ($deviceArray as $k => $v) {
            $deviceList[] = $v['catName'].'-'.$v['brandName'].'-'.$v['typeName'].'-'.$v['sub_id'];
        }
         
        return $deviceList;
    }
    
    /**
     * 批量设置计费规则
     * @return array|mixed
     */
    public function batchFeeTemplateSave($data)
    {
        $result = ['status' => false, 'msg' => '保存失败' , 'data' => ''];

        foreach (explode(',', $data['deviceIds']) as $id) {
            //设置计费规则关联
            $deviceTemplateRel = new DeviceTemplateRel();
        
            //清空所有的计费规则
            $deviceTemplateRel->where(['device_id'=>$id])->delete();
        
            if(isset($data['template_id'])){
                $data1 = [];
                foreach($data['template_id'] as $k => $v){
                    $row['device_id'] = $id;
                    $row['template_id'] = $k;
                    $data1[] = $row;
                }
                $deviceTemplateRel->saveAll($data1);
            }
        }

        $result['status'] = true;
        $result['msg']    = '保存成功'; 
        
        return $result;
    }
}